<template>
  <div class="w">
    <!-- 面包屑 -->
    <div class="title">
      <a href="#">首页</a> > <a href="#">购物车</a> > <a href="#">填写订单</a>
    </div>

    <div class="payContainer">
      <!-- 地址 -->
      <div class="addresss">
        <h5>收货地址</h5>
        <div class="addressInfo">
          <div class="addressUser">
            <ul v-if="newUserAddresses">
              <li><span>收货人: </span>{{ newUserAddresses.receiver }}</li>
              <li><span>联系方式: </span>{{ newUserAddresses.contact }}</li>
              <li><span>收货地址: </span>{{ newUserAddresses.address }}</li>
            </ul>
            <ul v-else>
              <li>请添加地址</li>
            </ul>
            <button class="addressUpdate" @click="addOrUpdateAddress(1)">
              修改地址
            </button>
          </div>
          <div class="addressUpdateOrPush">
            <button @click="changeAddress">切换地址</button>
            <button @click="addOrUpdateAddress(0)">添加地址</button>
          </div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="shop">
        <h5>商品信息</h5>
        <div class="shopInfo">
          <table>
            <thead>
              <tr>
                <td>商品信息</td>
                <td>单价</td>
                <td>数量</td>
                <td>小计</td>
                <td>实付</td>
              </tr>
            </thead>

            <tbody>
              <!-- 商品信息 -->
              <tr v-for="order in orderInfo" :key="order.id">
                <td class="imgBox">
                  <div>
                    <img :src="order.picture" alt="" />
                  </div>
                  <div class="imgInfo">
                    <p>{{ order.name }}</p>
                    <span>{{ order.attrsText }}</span>
                  </div>
                </td>
                <td>￥{{ order.payPrice }}</td>
                <td>{{ order.count }}</td>
                <td>￥{{ order.totalPrice }}</td>
                <td>￥{{ order.totalPrice }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 配送时间 -->
      <div class="time">
        <h5>配送时间</h5>

        <ul class="timeInfo">
          <li class="active">不限送货时间：周一至周日</li>
          <li>工作日送货：周一至周五</li>
          <li>双休日、假日送货：周六至周日</li>
        </ul>
      </div>

      <!-- 支付方式 -->
      <div class="pay">
        <h5>支付方式</h5>
        <ul class="payWay">
          <li class="active">在线支付</li>
          <li>货到付款</li>
          <span>货到付款需付5元手续费</span>
        </ul>
      </div>

      <!-- 金额明细 -->
      <div class="money">
        <h5>金额明显</h5>
        <ul class="moneyDetail">
          <li>
            <span>商品件数：</span><i>{{ orderPrice.goodsCount }}件</i>
          </li>
          <li>
            <span>商品总价：</span><i>￥{{ orderPrice.totalPrice }}</i>
          </li>
          <li>
            <span>运费：</span><i>￥{{ orderPrice.postFee }}</i>
          </li>
          <li>
            <span>应付总额：</span
            ><i class="allMoney">￥{{ orderPrice.totalPayPrice }}</i>
          </li>
        </ul>
      </div>

      <div class="submit">
        <button @click="submitOrder">提交订单</button>
      </div>
    </div>
  </div>

  <!-- 添加修改 对话框 -->
  <el-dialog
    v-model="Visible"
    :title="`${this.addOrUpdate === 0 ? '添加' : '修改'}收货地址`"
  >
    <template #default>
      <el-form
        :model="addressInfo"
        class="addressForm"
        label-width="100px"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="收货人" prop="receiver">
          <el-input
            placeholder="请输入收货人"
            v-model="addressInfo.receiver"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="contact">
          <el-input
            placeholder="请输入手机号"
            v-model="addressInfo.contact"
          ></el-input>
        </el-form-item>
        <el-form-item label="地区">
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedAddressOptions"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            placeholder="请输入详细地址"
            v-model="addressInfo.address"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮政编码" prop="postalCode">
          <el-input
            placeholder="请输入邮政编码"
            v-model="addressInfo.postalCode"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址标签" prop="addressTags">
          <el-input
            placeholder="请输入地址标签，逗号分隔"
            v-model="addressInfo.addressTags"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="Visible = false">取消</el-button>
        <el-button class="saveButton" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 切换地址对话框 -->
  <el-dialog v-model="changeVisible" title="切换地址" class="changeVisible">
    <ul
      v-for="user in userAddresses"
      :key="user.id"
      :class="{ active: user.isDefault === 0 }"
      @click="choseAddress(user, userAddresses)"
    >
      <li>
        <i>收货人:</i><span>{{ user.receiver }}</span>
      </li>
      <li>
        <i>联系方式:</i><span>{{ user.contact }}</span>
      </li>
      <li>
        <i>收货地址:</i><span>{{ user.address }} </span>
      </li>
    </ul>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="changeVisible = false">取消</el-button>
        <el-button
          type="primary"
          class="saveButton"
          @click="toggleAddress(userAddresses)"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script>
// import { threadId } from 'worker_threads'
// input 城市输入框
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'

import {
  addAddressRequest,
  choseAddressRequest,
  getOrderInfoRequest,
  updatedAddressRequest,
  submitOrderRequest,
} from '@/api/order'

export default {
  // eslint-disable-next-line comma-dangle
  name: 'XCheckout',
  dicts: ['sys_normal_disable', 'sys_user_sex'],

  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        const Reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
        if (!Reg.test(value)) {
          // this.$refs.ruleForm.validateField('contact')
          callback(new Error('请输入正确的手机号'))
        }
        callback()
      }
    }

    return {
      Visible: false, // 添加 修改对话框
      changeVisible: false, // 切换对话框
      // 表单数据
      addressInfo: {
        receiver: '', // 收货人
        contact: '', // 联系方式
        provinceCode: '', // 省份编码
        cityCode: '', // 所在城市编码
        countyCode: '', // 所在区/县编码
        address: '', // 详细地址
        postalCode: '', // 邮政编码
        addressTags: '', // 地址标签,以英文逗号分割
        isDefault: 1,
      },
      addOrUpdate: 0,
      // 校验规则
      rules: {
        receiver: [
          { required: true, message: '请输入收货人名称', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
        ],
        postalCode: [
          { required: true, message: '请输入邮政编码', trigger: 'blur' },
        ],
        addressTags: [
          { required: true, message: '请输入地址标签', trigger: 'blur' },
        ],
        contact: [{ validator: validatePhone, trigger: 'blur' }],
      },
      // 城市输入框数据
      options: regionData, // 城市数据
      selectedAddressOptions: [], // 选中数据
      // 商品数据
      orderInfo: [],
      orderPrice: [],
      userAddresses: [],
      newUserAddresses: [],
      ruleFormRef: '',
    }
  },
  methods: {
    // 添加地址
    async addOrUpdateAddress(num) {
      this.addOrUpdate = num
      if (num === 1) {
        // 修改地址按钮
        this.addressInfo = this.newUserAddresses
      } else {
        // await this.$nextTick(() => {
        // ruleFormRef = this.$refs.ruleForm
        // console.log(ruleFormRef)
        // })
      }
      this.Visible = true
    },
    // 地址输入框
    async handleChange(value) {
      this.addressInfo.provinceCode = value[0] + ''
      this.addressInfo.cityCode = value[1] + ''
      this.addressInfo.countyCode = value[2] + ''
    },
    // 提交表单
    async submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.addOrUpdate === 0) {
            // 添加功能
            await addAddressRequest({ ...this.addressInfo })
          } else {
            // console.log({ ...this.newUserAddresses })
            await updatedAddressRequest(this.newUserAddresses.id, {
              ...this.newUserAddresses,
            })
          }
        }
      })
      // this.Visible = false
    },
    // 切换地址按钮
    changeAddress() {
      this.changeVisible = true
      this.getOrderInfo()
    },
    // 选择地址切换样式
    choseAddress(user, userAddresses) {
      userAddresses.forEach((item) => {
        item.isDefault = 1
      })
      user.isDefault = 0
    },
    // 切换地址
    toggleAddress(userAddresses) {
      const newAddr = userAddresses.filter((item) => {
        return item.isDefault === 0
      })
      this.newUserAddresses = newAddr[0]
      console.log(this.newUserAddresses)
      this.selectedAddressOptions = [
        `${this.newUserAddresses.provinceCode}`,
        `${this.newUserAddresses.cityCode}`,
        `${this.newUserAddresses.countyCode}`,
      ]
      this.changeVisible = false
    },
    // 初次请求函数
    async getOrderInfo() {
      const result = await getOrderInfoRequest()
      console.log('result', result)
      this.orderInfo = result.goods
      this.orderPrice = result.summary
      this.userAddresses = result.userAddresses
      this.newUserAddresses = result.userAddresses[0]
      this.selectedAddressOptions = [
        `${this.newUserAddresses.provinceCode}`,
        `${this.newUserAddresses.cityCode}`,
        `${this.newUserAddresses.countyCode}`,
      ]
    },
    // 提交订单
    async submitOrder() {
      // this.$router.push('/member/pay')
      const goods = []
      const goodsInfo = {
        skuId: '',
        count: '',
      }
      // console.log(this.newUserAddresses)
      this.orderInfo.map((item) => {
        console.log(item)
        goodsInfo.skuId = item.skuId
        goodsInfo.count = item.count
        goods.push(goodsInfo)
        return goods
      })
      const addressId = this.newUserAddresses.id
      const deliveryTimeType = 1
      const payType = 1
      const buyerMessage = ''
      const data = { goods, addressId, deliveryTimeType, payType, buyerMessage }
      const result = await submitOrderRequest(data)
      console.log(result.result)
      this.$router.push({
        name: 'Pay',
        query: { orderId: result.id },
      })
    },
  },
  mounted() {
    this.getOrderInfo()
  },
}
</script>

<style scope>
* {
  margin: 0;
  padding: 0;
}

ul li {
  list-style: none;
}

body {
  background-color: #f5f5f5;
}

.w {
  width: 1240px;
  margin: 0 auto;
}

/* 面包屑 */
.title {
  height: 72px;
  line-height: 72px;
}

.title a {
  text-decoration: none;
  font-size: 14px;
  color: #666;
}

.payContainer {
  padding: 0 20px;
  background-color: #fff;
}

/* h5标题 */
h5 {
  height: 71px;
  line-height: 71px;
  padding: 0 10px;
  font-size: 16px;
  color: #333;
  font-weight: 400;
  border-bottom: 1px solid #f5f5f5;
}

/* 地址信息 */
.addressInfo {
  display: flex;
  margin: 20px 0;
  border: 1px solid #f5f5f5;
}

.addressUser {
  padding: 20px;
  display: flex;
}

.addressUser ul {
  width: 598px;
}

.addressUser ul li {
  height: 30px;
  line-height: 30px;
}

.addressUser ul li span {
  display: inline-block;
  width: 70px;
  font-size: 14px;
  color: #999;
}

.addressUpdate {
  width: 160px;
  background-color: transparent;
  border: 0;
  color: #27ba9b;
  font-size: 14px;
  cursor: pointer;
  border-right: 1px solid #f5f5f5;
}

.addressUpdateOrPush {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.addressUpdateOrPush button {
  width: 140px;
  height: 46px;
  font-size: 14px;
  background-color: transparent;
  border: 1px solid #e4e4e4;
  color: #666;
  margin-left: 20px;
}

/* 商品信息 */
.shopInfo {
  padding-top: 20px;
}

.shopInfo table {
  width: 100%;
  border-collapse: collapse;
}

.shopInfo thead {
  width: 100%;
  height: 60px;
  line-height: 60px;
  background-color: #f5f5f5;
  text-align: center;
}

.shopInfo tbody tr {
  border: 1px solid #f5f5f5;
}

.shopInfo tbody tr td {
  padding: 20px;
  text-align: center;
  /* display: flex; */
}

.shopInfo tbody tr .imgBox {
  display: flex;
  justify-content: flex-start;
}

.shopInfo tbody tr td img {
  width: 70px;
  margin-right: 20px;
}
.shopInfo tbody tr td .imgInfo {
  text-align: left;
}

.shopInfo tbody tr td .imgInfo p {
  color: #333;
  font-size: 14px;
}

.shopInfo tbody tr td .imgInfo span {
  color: #999;
  font-size: 14px;
}

/* 配送 */
.timeInfo {
  padding: 20px 0;
  display: flex;
}

.timeInfo li {
  width: 228px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #e4e4e4;
  margin-right: 25px;
  font-size: 14px;
  color: #666;
}

.timeInfo .active {
  border-color: #27ba9b;
}

/* 支付 */
.payWay {
  padding: 20px 0;
  display: flex;
}

.payWay li {
  width: 228px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #e4e4e4;
  margin-right: 25px;
  font-size: 14px;
  color: #666;
}

.payWay .active {
  border-color: #27ba9b;
}

.payWay span {
  line-height: 50px;
  font-size: 14px;
  color: #999;
}

/* 金额明细 */
.money {
  border-bottom: 1px solid #f5f5f5;
}

.moneyDetail {
  margin: 20px 0;
  text-align: right;
}

.moneyDetail li {
  height: 50px;
  padding-right: 70px;
  display: flex;
  justify-content: flex-end;
}

.moneyDetail li i {
  font-style: normal;
  color: #333;
  padding-left: 70px;
  font-size: 14px;
}

.moneyDetail li .allMoney {
  font-size: 20px;
  color: #cf4444;
}

.moneyDetail li span {
  width: 70px;
  color: #333;
  font-size: 14px;
}

/* 提交按钮 */
.submit {
  padding: 60px;
  height: 50px;
  text-align: right;
}

.submit button {
  width: 180px;
  height: 50px;
  font-size: 16px;
  border-radius: 4px;
  outline: none;
  border: 1px solid #27ba9b;
  background-color: #27ba9b;
  color: #fff;
  cursor: pointer;
}

/* dialog */
.el-dialog {
  width: 780px !important;
}
.addressForm {
  margin-left: 150px;
}

.addressForm .el-input {
  width: 320px;
  height: 50px;
}

.dialog-footer {
  text-align: center;
}
.dialog-footer button {
  width: 180px;
  height: 50px;
  color: #fff;
  background-color: #ccc;
}
.saveButton {
  background-color: #27ba9b !important;
}
/* 切换地址 */
.changeVisible {
  padding: 20px 40px;
  width: 600px;
}
.changeVisible ul {
  flex-direction: column;
  width: 520px;
  height: 112px;
  border: 1px solid #f5f5f5;
  margin-bottom: 10px;
}
.changeVisible ul li i {
  font-style: normal;
}
.changeVisible ul li {
  margin-top: 15px;
  margin-left: 10px;
}
.changeVisible .active {
  background-color: #e6faf6;
  border-color: #27ba9b;
}
.changeVisible ul:hover {
  background-color: #e6faf6;
  border-color: #27ba9b;
}
</style>